<script setup lang="ts">
/* eslint-disable no-console */
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { DictApi, QctemplateApi } from '#/api';

import { reactive, ref, watchEffect } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VxeButton } from '@vben/plugins/vxe-table';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteQctemplateindex,
  deleteQctemplateproduct,
  DictResp,
  getQctemplateindexList,
  getQctemplateproduct,
} from '#/api';
import { getToolBarBtns, setToolBarBtnDefaultDisabled } from '#/utils';

import {
  confirm,
  messageError,
  messageSuccess,
} from '../../../wm/common/common';
import editTemplateindex from './edit-templateindex.vue';
import editTemplateproduct from './edit-templateproduct.vue';

const props = defineProps(['template']);
const templateId = props.template;

watchEffect(() => {});
const mes_index_type = reactive<DictApi.SelectOption[]>([]);
DictResp(['mes_index_type']).then((res) => {
  console.log(res);

  // 将两个数组合并
  if (res.mes_index_type) {
    mes_index_type.push(...res.mes_index_type);
  }
});
// 存储选中行的响应式变量
const selectedRows = ref<QctemplateApi.Row1[]>([]);

const [Templateindex, editmodalApi1] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: editTemplateindex,
  destroyOnClose: true,
});

const [Templateproduct, editmodalApi2] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: editTemplateproduct,
  destroyOnClose: true,
});

// 表格左上角按钮
const buttons = getToolBarBtns();
const gridEvents1: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    console.log(code);
    switch (code) {
      case 'myAdd': {
        // console.log(templateId.value);

        // 新增逻辑
        console.log('新增');
        editmodalApi1
          .setData({ templateId })
          .setState({
            title: '添加检测模板-检测项',
          })
          .open();
        break;
      }
      case 'myDel': {
        // 删除逻辑
        // console.log('删除');
        deleteTemplateindex(selectedRows.value as any);
        break;
      }
      case 'myEdit': {
        // 保存逻辑
        alterTemplateindex(selectedRows.value[0] as any);
        console.log('修改');
        break;
      }
      default: {
        break;
      }
    }
  },
  checkboxChange({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
  checkboxAll({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
};

const gridEvents2: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    console.log(code);
    switch (code) {
      case 'myAdd': {
        // console.log(templateId);

        // 新增逻辑
        console.log('新增');
        editmodalApi2
          .setData({ templateId })
          .setState({
            title: '添加检测模板-产品',
          })
          .open();
        break;
      }
      case 'myDel': {
        // 删除逻辑
        // console.log('删除');
        deleteTemplateproduct(selectedRows.value as any);
        break;
      }
      case 'myEdit': {
        // 保存逻辑
        alterTemplateproduct(selectedRows.value[0] as any);
        console.log('修改');
        break;
      }
      default: {
        break;
      }
    }
  },
  checkboxChange({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
  checkboxAll({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
};

const gridOptions1 = reactive<VxeGridProps<QctemplateApi.Row1>>({
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    {
      align: 'left',
      field: 'indexId',
      title: '',
      type: 'checkbox',
      width: 50,
    },
    { field: 'indexName', title: '检测项名称' },
    {
      field: 'indexType',
      title: '检测项类型',
      formatter: ({ cellValue }) => {
        const item = mes_index_type.find((item) => item.value === cellValue);
        return item?.label || '';
      },
    },
    { field: 'qcTool', title: '检测工具' },
    { field: 'checkMethod', title: '检测方法' },
    { field: 'standerVal', title: '标准值' },
    { field: 'unitOfMeasure', title: '单位' },
    { field: 'thresholdMax', title: '误差上限' },
    { field: 'thresholdMin', title: '误差下限' },
    { slots: { default: 'action' }, fixed: 'right', title: '操作' },
  ],
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const res = await getQctemplateindexList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          templateId: templateId as any,
        });
        return {
          total: res.total,
          items: res.rows,
        };
      },
    },
  },

  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    refresh: true,
    buttons: buttons.value,
  },
});

const gridOptions2 = reactive<VxeGridProps<QctemplateApi.Row>>({
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    {
      align: 'left',
      field: 'itemId',
      title: '',
      type: 'checkbox',
      width: 50,
    },
    { field: 'itemCode', title: '产品物料编码' },
    { field: 'itemName', title: '产品物料名称' },
    { field: 'specification', title: '规格型号' },
    { field: 'quantityCheck', title: '最低检测数' },
    { field: 'unitName', title: '单位' },
    { field: 'quantityUnqualified', title: '最大不合格数' },
    {
      field: 'crRate',
      title: '最大致命缺陷率',
      formatter: ({ cellValue }) => {
        return `${cellValue}%`;
      },
    },
    {
      field: 'majRate',
      title: '最大严重缺陷率',
      formatter: ({ cellValue }) => {
        return `${cellValue}%`;
      },
    },
    {
      field: 'minRate',
      title: '最大轻微缺陷率',
      formatter: ({ cellValue }) => {
        return `${cellValue}%`;
      },
    },
    { slots: { default: 'action' }, fixed: 'right', title: '操作' },
  ],
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const res = await getQctemplateproduct({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          templateId: templateId as any,
        });
        return {
          total: res.total,
          items: res.rows,
        };
      },
    },
  },

  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    refresh: true,
    buttons: buttons.value,
  },
});

function alterTemplateindex(row: QctemplateApi.Row1) {
  console.log(row);
  editmodalApi1
    .setState({
      title: '修改检测模板-检测项',
    })
    .setData(row)
    .open();
}
function alterTemplateproduct(row: QctemplateApi.Row2) {
  console.log(row);
  editmodalApi2
    .setState({
      title: '修改检测模板-产品',
    })
    .setData(row)
    .open();
}

function deleteTemplateindex(row: QctemplateApi.Row1) {
  console.log(row);
  const ids = Array.isArray(row)
    ? row.map((item) => item.recordId)
    : [row.recordId];
  const idString = ids.join(',');
  confirm(
    `是否确认删除检测模板-检测项编号为${idString}的数据吗？`,
    '提示',
  ).then(() => {
    deleteQctemplateindex(idString)
      .then(() => {
        refreshGrid(`删除成功`);
      })
      .catch((error) => {
        messageError(error);
      });
  });
}
function deleteTemplateproduct(row: QctemplateApi.Row2) {
  console.log(row);
  const ids = Array.isArray(row)
    ? row.map((item) => item.recordId)
    : [row.recordId];
  const idString = ids.join(',');
  confirm(`是否确认删除检测模板-产品编号为${idString}的数据吗？`, '提示').then(
    () => {
      deleteQctemplateproduct(idString)
        .then(() => {
          refreshGrid(`删除成功`);
        })
        .catch((error) => {
          messageError(error);
        });
    },
  );
}

// 获取弹框中检测项表格
const [Grid1, grid1Api] = useVbenVxeGrid({
  gridOptions: gridOptions1,
  gridEvents: gridEvents1,
});

// 获取弹框中物料产品表格
const [Grid2, grid2Api] = useVbenVxeGrid({
  gridOptions: gridOptions2,
  gridEvents: gridEvents2,
});

function refreshGrid(msg: string) {
  messageSuccess(msg);
  grid1Api.query();
  grid2Api.query();
}
</script>

<template>
  <div>
    <Templateindex @success="refreshGrid" />
    <Templateproduct @success="refreshGrid" />
    <el-tabs type="border-card">
      <el-tab-pane label="检测项">
        <Grid1>
          <template #action="{ row }">
            <VxeButton
              mode="text"
              icon="vxe-icon-signature"
              @click="alterTemplateindex(row)"
              status="primary"
            >
              修改
            </VxeButton>
            <VxeButton
              icon="vxe-icon-delete"
              mode="text"
              @click="deleteTemplateindex(row)"
              status="error"
            >
              删除
            </VxeButton>
          </template>
        </Grid1>
      </el-tab-pane>
      <el-tab-pane label="物料产品">
        <Grid2>
          <template #action="{ row }">
            <VxeButton
              mode="text"
              icon="vxe-icon-signature"
              @click="alterTemplateproduct(row)"
              status="primary"
            >
              修改
            </VxeButton>
            <VxeButton
              icon="vxe-icon-delete"
              mode="text"
              @click="deleteTemplateproduct(row)"
              status="error"
            >
              删除
            </VxeButton>
          </template>
        </Grid2>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
